﻿using Microsoft.Media.IngestClient;
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage.Streams;

namespace Microsoft.Media.CaptureClient
{
    /// <summary>
    /// Implementation of IPushOutputConsumer that can stream the output from PushClient to a stream.
    /// Useful for debugging and writing output to local file system.
    /// </summary>
    internal class StreamOutputConsumer : IPushOutputConsumer
    {
        public uint BufferSize { get; set; }

        IOutputStream outputStream;
        bool closeOnTerminate;

        public StreamOutputConsumer(IOutputStream outputStream, bool closeOnTerminate)
        {
            BufferSize = 1024;
            this.outputStream = outputStream;
            this.closeOnTerminate = closeOnTerminate;
        }

        public IAsyncActionWithProgress<ulong> SendDataAsync(IInputStream inputStream)
        {
            return AsyncInfo.Run((CancellationToken c, IProgress<ulong> p) => SendDataAsync(inputStream, p, c));
        }

        internal async Task SendDataAsync(IInputStream inputStream, IProgress<ulong> progress, CancellationToken c)
        {
            ulong bytesRead = 0UL;
            do
            {
                var buffer = await inputStream.ReadAsync(null, BufferSize, InputStreamOptions.None).AsTask(c);
                if (buffer.Length == 0) break;

                await outputStream.WriteAsync(buffer).AsTask(c);
                await outputStream.FlushAsync().AsTask(c);

                bytesRead += buffer.Length;
                progress.Report(bytesRead);
            } while (true);
        }

        public IAsyncAction TerminateAsync()
        {
            return _TerminateAsync().AsAsyncAction();
        }

        async Task _TerminateAsync()
        {
            await outputStream.FlushAsync();
            if (closeOnTerminate) outputStream.Dispose();
        }
    }
}
